package com.atguigu.hadoop.examples.mapreduce;


import com.google.common.base.Charsets;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class WordMean extends Configured
        implements Tool
{
    private double mean = 0.0D;

    private static final Text COUNT = new Text("count");
    private static final Text LENGTH = new Text("length");
    private static final LongWritable ONE = new LongWritable(1L);

    private double readAndCalcMean(Path path, Configuration conf)
            throws IOException
    {
        FileSystem fs = FileSystem.get(conf);
        Path file = new Path(path, "part-r-00000");

        if (!fs.exists(file)) {
            throw new IOException("Output not found!");
        }
        BufferedReader br = null;
        try
        {
            br = new BufferedReader(new InputStreamReader(fs.open(file), Charsets.UTF_8));

            long count = 0L;
            long length = 0L;
            String line;
            String lengthLit;
            while ((line = br.readLine()) != null) {
                StringTokenizer st = new StringTokenizer(line);

                String type = st.nextToken();

                if (type.equals(COUNT.toString())) {
                    String countLit = st.nextToken();
                    count = Long.parseLong(countLit);
                } else if (type.equals(LENGTH.toString())) {
                    lengthLit = st.nextToken();
                    length = Long.parseLong(lengthLit);
                }
            }

            double theMean = length / count;
            System.out.println("The mean is: " + theMean);
            return theMean;
        } finally {
            if (br != null)
                br.close();
        }
    }

    public static void main(String[] args) throws Exception
    {
        ToolRunner.run(new Configuration(), new WordMean(), args);
    }

    public int run(String[] args) throws Exception
    {
        if (args.length != 2) {
            System.err.println("Usage: wordmean <in> <out>");
            return 0;
        }

        Configuration conf = getConf();

        Job job = Job.getInstance(conf, "word mean");
        job.setJarByClass(WordMean.class);
        job.setMapperClass(WordMeanMapper.class);
        job.setCombinerClass(WordMeanReducer.class);
        job.setReducerClass(WordMeanReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);
        FileInputFormat.addInputPath(job, new Path(args[0]));
        Path outputpath = new Path(args[1]);
        FileOutputFormat.setOutputPath(job, outputpath);
        boolean result = job.waitForCompletion(true);
        this.mean = readAndCalcMean(outputpath, conf);

        return result ? 0 : 1;
    }

    public double getMean()
    {
        return this.mean;
    }

    public static class WordMeanReducer extends Reducer<Text, LongWritable, Text, LongWritable>
    {
        private LongWritable sum = new LongWritable();

        public void reduce(Text key, Iterable<LongWritable> values, Reducer<Text, LongWritable, Text, LongWritable>.Context context)
                throws IOException, InterruptedException
        {
            int theSum = 0;
            for (LongWritable val : values) {
                theSum = (int)(theSum + val.get());
            }
            this.sum.set(theSum);
            context.write(key, this.sum);
        }
    }

    public static class WordMeanMapper extends Mapper<Object, Text, Text, LongWritable>
    {
        private LongWritable wordLen = new LongWritable();

        public void map(Object key, Text value, Mapper<Object, Text, Text, LongWritable>.Context context)
                throws IOException, InterruptedException
        {
            StringTokenizer itr = new StringTokenizer(value.toString());
            while (itr.hasMoreTokens()) {
                String string = itr.nextToken();
                this.wordLen.set(string.length());
                context.write(WordMean.LENGTH, this.wordLen);
                context.write(WordMean.COUNT, WordMean.ONE);
            }
        }
    }
}